package com.ljw.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ljw.dto.BookDto;
import com.ljw.dto.UnBookDto;
import com.ljw.entity.Book;
import com.ljw.entity.Booksum;
import com.ljw.service.BookService;
import com.ljw.service.BooksumService;
import com.ljw.service.UserService;
import com.ljw.vo.BookVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * <p>
 * 预订信息表 前端控制器
 * </p>
 *
 * @author ljw
 * @since 2020-07-25
 */
@RestController
@RequestMapping("/book")
public class BookController {

    @Autowired
    private UserService userService;

    @Autowired
    private BookService bookService;

    @Autowired
    private BooksumService booksumService;

    @PostMapping("/book")
    @Transactional
    public Integer book(@RequestBody BookDto bookDto){
        return bookService.book(bookDto);
    }

    @PostMapping("/unBook")
    @Transactional
    public String unBook(@RequestBody UnBookDto unBookDto){
        Book book = bookService.getById(unBookDto.getBookId());
        if(book == null) return "ERROR";
        //insert into booksum
        Date date = new Date();
        Booksum booksum = new Booksum();
        booksum.setBooksumCreateBy(unBookDto.getCreateBy());
        booksum.setBooksumCreateTime(date);
        booksum.setBooksumInDate(book.getBookInDate());
        booksum.setBooksumOutDate(book.getBookOutDate());
        booksum.setBooksumRoomId(book.getBookRoomId());
        booksum.setBooksumType("退订");
        booksum.setBooksumOrderNum(book.getBookOrderNum());
        booksum.setBooksumUserId(book.getBookUserId());
        booksum.setBooksumSumPrice(book.getBookSumPrice());
        booksumService.save(booksum);
        //update book
        bookService.removeById(unBookDto.getBookId());
        return "OK";
    }

    @GetMapping("/findAll")
    public Page<BookVo> findAll(@RequestParam int userId, @RequestParam int current, @RequestParam int size){
        int userPower = userService.getById(userId).getUserPower();
        Page<BookVo> page = new Page<>(current,size);
        if(userPower == 1){
            return bookService.findAll(page,0);
        }else {
            return bookService.findAll(page,userId);
        }
    }

}

